import { useAppSelector } from "@/stores"
import { usePathname } from "next/navigation"
import { findAllMenuByPath } from "../../config/menu"
import AccessEnum from "./assess-enum"
import checkAccess from "./check-access"
import Forbidden from "@/app/forbidden"

/**
 * 统一权限校验拦截器
 */
const AccessLayout: React.FC<
  Readonly<{
    children: React.ReactNode
  }>
> = ({ children }) => {
  // 当前页面路径
  const pathname = usePathname()
  // 当前登录用户
  const loginUser = useAppSelector((state) => state.loginUser)
  // 获取当前页面的菜单
  const menu = findAllMenuByPath(pathname)
  // 获取当前页面的访问权限
  const access = menu?.access ?? AccessEnum.NOT_LOGIN
  const canAccess = checkAccess(loginUser, access)
  if (!canAccess) {
    return <Forbidden />
  }

  return <>{children}</>
}

export default AccessLayout
